<!--树 多选框-->
<template>
  <el-dropdown ref="baseTreeMultipleDrop" trigger="click" @click.native="stop">
    <el-input v-model="label" :disabled="disabled" :placeholder="placeholder" />
    <el-dropdown-menu
      slot="dropdown"
      class="base-tree-multiple"
      :disabled="disabled"
    >
      <el-tree
        ref="baseTreeMultiple"
        :data="treeData"
        show-checkbox
        node-key="id"
        :props="{ children: 'children', label: 'name' }"
        :check-strictly="isCheck"
        @check="checkPosition"
      >
      </el-tree>
    </el-dropdown-menu>
  </el-dropdown>
</template>

<script>
export default {
  name: "BaseTreeMultiple",
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: "请选择",
    },
    treeData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      label: "",
      isCheck: false,
    };
  },
  watch: {
    value: function() {
      this.setDefaultNode();
    },
  },
  methods: {
    stop() {
      if (this.disabled) {
        this.$refs.baseTreeMultipleDrop.hide();
      }
    },
    setDefaultNode() {
      this.isCheck = true;
      if (!this.value.length) {
        this.label = "";
      }

      this.$refs.baseTreeMultiple.setCheckedKeys(this.value);
      this.$nextTick(() => {
        this.isCheck = false;
        const checkedNodes = this.$refs.baseTreeMultiple.getCheckedNodes();
        if (checkedNodes && checkedNodes.length) {
          this.label = checkedNodes.map((v) => v.name).join(",");
        } else {
          this.label = "";
        }
      });
    },
    checkPosition(node, data) {
      let checkStr = [];
      if (data.checkedNodes && data.checkedNodes.length) {
        checkStr = data.checkedNodes
          .filter((v) => !v.children || !v.children.length)
          .map((v) => v.label);
      }
      this.label = checkStr.length ? checkStr.join(",") : "";
      this.$emit("input", data.checkedKeys);
    },
  },
};
</script>

<style lang="scss">
.base-tree-multiple {
  width: 210px;
  max-height: 500px;
  overflow: auto;
}
/*此处是为了添加横向滚动条*/
.el-tree > .el-tree-node {
  min-width: 100%;

  display: inline-block;
}
</style>
